<template>
  <div class="warp">
    <div class="title">
      列表
      <div class="logout-btn" @click="logout">注销登录</div>
    </div>
    <div class="select-file">
      <el-dropdown @command="handleCommand" size="large">
        <span class="el-dropdown-link header-title">
          {{ ItemFileInfo.title }} -- ({{ ItemFileInfo.isDelete ? "已删除" : "正常" }})
          <el-icon class="el-icon--right">
            <arrow-down />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              :class="ItemFileInfo.uuid === item.uuid ? 'selected' : ''"
              v-for="item in directoryList"
              :key="item.uuid"
              :command="item"
              >{{ item.title
              }}{{
                item.uuid !== "add" ? (item.isDelete ? "——已删除" : "——正常") : ""
              }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div>
        <el-button type="primary" :icon="Edit" circle @click="updateTitle" />
        <el-button
          v-if="ItemFileInfo.isDelete"
          type="warning"
          :icon="Check"
          circle
          @click="restoreItemFile"
        />
        <el-button v-else type="danger" :icon="Delete" circle @click="deleteItemFile" />
      </div>
    </div>
    <el-upload
      v-model:file-list="fileList"
      class="upload-demo"
      :action="action"
      :headers="headers"
      :on-success="handleSuccess"
      :before-remove="beforeRemove"
      :on-remove="handleRemove"
      :multiple="false"
      :limit="1"
      list-type="picture"
      accept="image/png, image/jpg"
    >
      <el-button type="primary">上传封面</el-button>
      <template #tip>
        <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </template>
    </el-upload>
    <ul class="url-list">
      <li class="url-list-item" v-for="item in ItemFileInfo.items" :key="item.id">
        <div class="info">
          <div>{{ item.label }}</div>
          <div>{{ item.url }}</div>
        </div>
        <div class="btn-group">
          <div class="btn" @click="editItem(item)">编辑</div>
          <div class="btn" @click="deleteItem(item)">删除</div>
        </div>
      </li>
    </ul>
    <div class="add-btn" @click="addItem()">新增</div>
    <!-- 添加培训班弹框 -->
    <el-dialog v-model="addFormVisible" :title="isAdd ? '新增培训班' : '编辑培训班'">
      <el-form>
        <el-form-item label="标题">
          <el-input v-model="addFormTitle" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFormCancel">取消</el-button>
          <el-button type="primary" @click="addFormSave"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from "vue";
import { useUserStore } from "@/store/modules/user";
import { RouteParamValueRaw, RouteParamsRaw, useRouter } from "vue-router";
import { useItemsStore } from "@/store/modules/items";
import { storeToRefs } from "pinia";
import { FileItem, ItemFileInfo, ItemInfo } from "@/api/types/index";
import { ElMessage, ElMessageBox, UploadProps } from "element-plus";
import { Edit, Delete, Check } from "@element-plus/icons-vue";
const router = useRouter();
const _useUserStore = useUserStore();
const _useItemsStore = useItemsStore();
const { DIRECTORY_LIST } = storeToRefs(_useItemsStore);
const ItemFileInfo = ref<ItemFileInfo>({
  uuid: "",
  coverImage: "",
  dateTime: "",
  title: "",
  isDelete: false,
  items: [] as ItemInfo[],
});
const getInfo = (uuid: string) => {
  _useItemsStore
    .getItemFileInfo(uuid)
    .then((result) => {
      ItemFileInfo.value = result.data;
      if (ItemFileInfo.value.coverImage) {
        fileList.value = [
          {
            name: ItemFileInfo.value.title,
            url: import.meta.env.VITE_BASE_IMAGE_URL + ItemFileInfo.value.coverImage,
          },
        ];
      } else {
        fileList.value = [];
      }
    })
    .catch((err) => {});
};
const logout = (e) => {
  _useUserStore
    .logout()
    .then((result) => {
      if (result.code === 200) {
        router.push({
          path: "/login",
        });
      }
    })
    .catch((err) => {});
};
const action = ref("");
const headers = ref(null);
const fileList = ref([]);
const editItem = (item: ItemInfo) => {
  router.push({
    path: "/edit",
    query: { id: item.id },
  });
};
const deleteItem = (item: ItemInfo) => {
  ElMessageBox.confirm("确认删除吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(() => {
      _useItemsStore
        .deleteItem(item.id)
        .then((result) => {
          getInfo(ItemFileInfo.value.uuid);
        })
        .catch((err) => {});
    })
    .catch(() => {});
};
const addItem = () => {
  router.push({
    path: "/edit",
  });
};
const handleSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  if (response.statusCode === 200) {
    _useItemsStore
      .saveItemFile(ItemFileInfo.value.uuid, response.data, ItemFileInfo.value.title)
      .then((result) => {
        getInfo(ItemFileInfo.value.uuid);
      })
      .catch((err) => {});
  }
};
const restoreItemFile = () => {
  ElMessageBox.confirm("确认恢复当前培训班吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(() => {
      _useItemsStore
        .restoreItemFile(ItemFileInfo.value.uuid)
        .then((result) => {
          ElMessage({
            message: "恢复成功",
            type: "success",
          });
          getInfo(ItemFileInfo.value.uuid);
        })
        .catch((err) => {});
    })
    .catch(() => {});
};
const deleteItemFile = () => {
  ElMessageBox.confirm("确认删除当前培训班吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(() => {
      _useItemsStore
        .deleteItemFile(ItemFileInfo.value.uuid)
        .then((result) => {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          getInfo(ItemFileInfo.value.uuid);
        })
        .catch((err) => {});
    })
    .catch(() => {});
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm("确认删除图片?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  }).then(
    () => true,
    () => false
  );
};
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  _useItemsStore
    .saveItemFile(ItemFileInfo.value.uuid, "", ItemFileInfo.value.title)
    .then((result) => {
      getInfo(ItemFileInfo.value.uuid);
    })
    .catch((err) => {});
};
const selectDirectory = ref("");
const directoryList = computed(() => {
  return [
    { uuid: "add", title: "添加培训班", dateTime: "", isDelete: false },
    ...DIRECTORY_LIST.value,
  ];
});
const handleCommand = (command: FileItem) => {
  if (command.uuid === "add") {
    isAdd.value = true;
    addFormVisible.value = true;
  } else {
    getInfo(command.uuid);
  }
};

//#region 新增弹框

const isAdd = ref(true);
const addFormVisible = ref(false);
const addFormTitle = ref("");
const addFormCancel = () => {
  addFormVisible.value = false;
  addFormTitle.value = "";
};
const addFormSave = () => {
  let uuid = "";
  let url = "";
  if (!isAdd.value) {
    uuid = ItemFileInfo.value.uuid;
    url = ItemFileInfo.value.coverImage;
  }
  _useItemsStore
    .saveItemFile(uuid, url, addFormTitle.value)
    .then((result) => {
      console.log(result);
      getInfo(result.data);
      addFormCancel();
    })
    .catch((err) => {});
};
const updateTitle = () => {
  isAdd.value = false;
  addFormVisible.value = true;
  addFormTitle.value = ItemFileInfo.value.title;
};

//#endregion 新增弹框

onMounted(() => {
  action.value = import.meta.env.VITE_BASE_API + "/File/UploadFile";
  headers.value = {
    Authorization: "Bearer " + _useUserStore.token,
  };
  if (DIRECTORY_LIST.value && DIRECTORY_LIST.value.length) {
    if (_useItemsStore.nowFileItem.uuid) {
      selectDirectory.value = _useItemsStore.nowFileItem.uuid;
    } else {
      selectDirectory.value = DIRECTORY_LIST.value[0].uuid;
    }
    getInfo(selectDirectory.value);
  }
});
</script>
<style lang="scss" scoped>
@media screen and (min-width: 768px) {
  .warp {
    width: 600px;
    margin: auto;
  }
}
.warp {
  height: 100vh;
  .title {
    text-align: center;
    font-size: 24px;
    line-height: 50px;
  }
  .select-file {
    padding-top: 10px;
    padding-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .upload-demo {
    height: 160px;
  }
  .url-list {
    list-style-type: none;
    padding: 0;
    .url-list-item {
      padding-left: 10px;
      background-color: white;
      line-height: 30px;
      display: flex;
      justify-content: space-between;
      border-bottom: 2px solid #cccccc;
      .info {
        width: calc(100% - 50px);
      }
      .btn-group {
        .btn {
          cursor: pointer;
          line-height: 22px;
          margin: 5px;
          height: 24px;
          padding: 0 5px;
          border: 1px solid #e9e9e9;
          border-radius: 5px;
          font-size: 12px;
        }
      }
    }
  }
  .add-btn {
    cursor: pointer;
    width: 160px;
    height: 35px;
    text-align: center;
    margin: 10px auto;
    line-height: 33px;
    border-radius: 5px;
    border: 1px solid #15a5f1;
    color: #15a5f1;
  }
  .logout-btn {
    cursor: pointer;
    width: 80px;
    height: 24px;
    text-align: center;
    margin: 12px auto;
    line-height: 22px;
    border-radius: 5px;
    border: 1px solid #f56c6c;
    color: #f56c6c;
    font-size: 14px;
    float: right;
  }
}
</style>
<style>
.selected {
  color: #15a5f1 !important;
}
</style>
